package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.project.config.SystemConfig;
import com.example.project.constant.Constants;
import com.example.project.mapper.FileMapper;
import com.example.project.service.FileService;
import com.example.project.utils.FileMangerUtils;
import com.example.project.vo.model.FileVo;
import com.example.project.vo.model.SaveFile;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.List;

import static com.example.project.utils.FileMangerUtils.upLoad;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper fileMapper;

    @Resource
    private SystemConfig config;


    @Override
    public void downOne(String path, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=utf-8");

        // 组装path
        path = Constants.PROJECT_ROOT_DIRECTORY + config.getSystemName()+"/"+path;
        File tempFile = new File(path);
        InputStream inputStream = Files.newInputStream(tempFile.toPath());
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[2048];
        int len = 0;
        while ((len = inputStream.read(buff)) > 0) {
            outputStream.write(buff, 0, len);
            outputStream.flush();
        }
        inputStream.close();


    }

    @Override
    public void upload(FileVo fileVo) {

        SaveFile saveFile = FileMangerUtils.createSaveFile(fileVo.getFile());
        try {
            upLoad(saveFile, fileVo.getFile());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        com.example.project.entity.File  fileEn = new com.example.project.entity.File();
        BeanUtils.copyProperties(saveFile,fileEn);
        fileEn.setNoId(fileVo.getNoId());
        fileEn.setType(fileVo.getType());

        fileMapper.insert(fileEn);

    }

    @Override
    public void downPressOne(Long id, Integer type, HttpServletResponse response) {

    }


    @Override
    public List<com.example.project.entity.File> getFiles(int type, Long noId) {
        List<com.example.project.entity.File> files = fileMapper.selectList(new LambdaQueryWrapper<com.example.project.entity.File>()
                .eq(com.example.project.entity.File::getNoId, noId)
                .eq(com.example.project.entity.File::getType, type));
        return files;
    }
}
